﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web;
using System.Configuration;
namespace Enring.Global
{
    public class Installer : EnringPage
    {
        protected enum IntegratedSecurity{
            False,
            SSPI,
            True
        }
        protected enum ConnectionResult { 
            Faild,
            JustServerOK,
            ExistsDatabase,
        }
        protected class Result {
            public Exception Exception { get; set; }
            public bool Return { get; set; }
        }
        protected class SqlConnectionInfo:IDisposable {

            private string sysSqlCMD = "select * from sys.databases where name='{0}'";
            private string masterDB = "master";
            private string uidConn = "Data Source={0};User ID={1};Password={2};Initial Catalog={3};";
            private string sspiConn = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};";

            public SqlException Error { get; set; }
            public string DataSource { get; set; }
            public string UserID { get; set; }
            public string Password { get; set; }
            public string InitialCatalog { get; set; }
            public IntegratedSecurity IntegratedSecurity{get;set;}
            public string ToString(string dbnme)
            {
                if (UserID.Trim() == string.Empty)
                    IntegratedSecurity = Installer.IntegratedSecurity.SSPI;
                
                if(IntegratedSecurity == Installer.IntegratedSecurity.False)
                    return String.Format(uidConn, new string[] { DataSource , UserID , Password , dbnme   });
                else
                    return String.Format(sspiConn, DataSource ,dbnme );

            }
            public override string ToString()
            {
                return ToString(InitialCatalog);
            }
            private string ToStringByMaster() {

                return ToString(masterDB);
            }
            public SqlConnectionInfo() {
                IntegratedSecurity = Installer.IntegratedSecurity.False;
            }
            public SqlConnectionInfo(string sqlconnstr) {
                IntegratedSecurity = Installer.IntegratedSecurity.False;
                string[] strgroup = sqlconnstr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string str in strgroup) {
                    string[] frag = str.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    switch (frag[0].ToLower()){
                        case "data source":
                            DataSource = frag[1];
                            break;
                        case "integrated security":
                            if (frag[1].ToLower() == "sspi")
                                IntegratedSecurity = Installer.IntegratedSecurity.SSPI;
                            else if (frag[1].ToLower() == "true")
                                IntegratedSecurity = Installer.IntegratedSecurity.True;
                            else
                                IntegratedSecurity = Installer.IntegratedSecurity.False ;
                            break;
                        case "user id":
                            UserID = frag[1];
                            break;
                        case "password":
                            Password = frag[1];
                            break;
                        case "initial catalog":
                            InitialCatalog = frag[1];
                            break;
                    }
                }
                
            }

       

            /// <summary>
            /// Test Connection Server\User ID\Password
            /// </summary>
            /// <param name="server">IP or ServerName or SQL Instance</param>
            /// <param name="uid">User Id</param>
            /// <param name="pwd">Password </param>
            /// <returns>bool true or false</returns>
            public ConnectionResult TestConnection()
            {
                ConnectionResult rst = ConnectionResult.Faild;
                using (SqlConnection sqlConn = new SqlConnection())
                {
                    sqlConn.ConnectionString = ToStringByMaster();
                    try
                    {
                        sqlConn.Open();
                        SqlCommand cmd = sqlConn.CreateCommand();
                        cmd.CommandText = string.Format(sysSqlCMD,InitialCatalog);
                        object rtn = cmd.ExecuteScalar();
                        if (rtn == null)
                            rst = ConnectionResult.JustServerOK;
                        else
                            rst = ConnectionResult.ExistsDatabase;
                    }
                    catch(SqlException err)
                    {
                        Error = err;
                        rst = ConnectionResult.Faild;
                    }
                    finally
                    {
                        sqlConn.Close();
                    }
                }
                return rst;
            }


            public void Dispose()
            {
               
            }
        }
        /// <summary>
        /// modify web.config ConnectionStrings scene.create EnringContext ;
        /// </summary>
        /// <param name="server">IP or ServerName or SQL Instance</param>
        /// <param name="uid">User Id</param>
        /// <param name="pwd">Password </param>
        /// <param name="database">database name</param>
        /// <returns>result class true or false</returns>
        protected bool ModifyWebConfig(SqlConnectionInfo sqlconninfo)
        {
            try
            {
                string connstr = sqlconninfo.ToString();
                Configuration cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
                cfg.ConnectionStrings.ConnectionStrings["EnringContext"].ProviderName = "System.Data.SqlClient";
                cfg.ConnectionStrings.ConnectionStrings["EnringContext"].ConnectionString = connstr;
                cfg.Save();
                return true;
            }
            catch (Exception err) {
                throw err;
            }
        }

        
    }
}
